#include "clusterclient.h"

HmiClient::HmiClient(const std::string &target)
    : GrpcUtilsClientS<task_flow::TaskFlowServer::Stub>(target) {}

HmiClient::~HmiClient() { stop(); }

int HmiClient::start()
{
    if (is_running_)
    {
        LOG(ERROR) << "already run";
        return -1;
    }
    is_running_ = true;
    monitor_thread_ =
        std::make_shared<std::thread>(&HmiClient::monitorLoop, this);
    return 1;
}

void HmiClient::monitorLoop()
{
    // 周期性调用服务器接口获取信息
    // 通过回调函数通知上层
    while (is_running_)
    {
        std::this_thread::sleep_for(std::chrono::milliseconds(1000));
        task_flow::Void _;
        task_flow::GraphInfo graph_info;
        grpc::Status status;
        status = CallRpc(&task_flow::TaskFlowServer::Stub::GetGraphInfo, _,
                         graph_info, 1000);
        if (status.ok())
        {
            if (monitor_cb_)
            {
                monitor_cb_(graph_info);
            }
        }
        else
        {
            LOG(ERROR) << "grpc GetGraphInfo() failed";
        }
    }
}

void HmiClient::stop()
{
    if (is_running_)
    {
        is_running_ = false;
        monitor_thread_->join();
        monitor_thread_.reset();
    }
}

void HmiClient::setCallback(MonitorCallback monitor_cb)
{
    monitor_cb_ = monitor_cb;
}